/**
 * Created by li hong 2017/10/25 0025.
 */
var wind = null;
//日期转换
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
$(function () {
    $.ajaxSettings.async = false; //设置ajax请求为同步请求，默认是异步加载（在页面请求的时候，首先设置。不然数据可能会丢失）
    var table = new tableFactory();
    addListeners(table);


    /*layer,open日期事件*/
    $(document).on('click', function () {
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            laydate.render({
                elem: '#new-publishtime', //新增的日期
                type: 'datetime',
                trigger: 'click'
            });
            laydate.render({
                elem: '#new-starttime', //新增的日期
                type: 'datetime',
                trigger: 'click'
            });
            laydate.render({
                elem: '#new-endtime', //新增的日期
                type: 'datetime',
                trigger: 'click'
            });
            laydate.render({
                elem: '#edit-publishtime', //修改的日期
                type: 'datetime',
                trigger: 'click'
            });
            laydate.render({
                elem: '#edit-starttime', //修改的日期
                type: 'datetime',
                trigger: 'click'
            });
            laydate.render({
                elem: '#edit-endtime', //修改的日期
                type: 'datetime',
                trigger: 'click'
            });

        });
    });
});

function tableFactory() {
    var me = this;
    me.data = null;
    me.WindData = null;
    var init = function () {
        $.when(me.getWindData()).then(function () {
            $("#planXd").bootstrapTable({
                method: 'get',					  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "asc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: true,			  //是否显示刷新按钮
                clickToSelect: true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: false,                //是否支持多选,false表示支持多选，true表示不支持
                //undefinedText: '_',              //当数据为undefined时显示的字符
                height: 'auto',
                pageSize: 10,
                pageList: [5, 10, 20],
                columns: [{
                    field: 'check',
                    checkbox: true
                }, {
                    title: '类型', field: 'typeName', align: 'center', valign: 'middle',
                    formatter: function (value, row, index) {
                        return me.getWindById(row.type);
                    }
                }, {
                    title: '发布时间',
                    field: 'publicTime',
                    align: 'center',
                    valign: 'middle',
                    /*formatter: function (value, row, index) {
                        return new Date(parseInt(value)).Format("yyyy-MM-dd hh:mm");
                    }*/
                }, {
                    title: '开始时间',
                    field: 'startTime',
                    align: 'center',
                    valign: 'middle',
                    /*formatter: function (value, row, index) {
                        return new Date(parseInt(value)).Format("yyyy-MM-dd hh:mm");
                    }*/
                }, {
                    title: '结束时间',
                    field: 'endTime',
                    align: 'center',
                    valign: 'middle',
                    /*formatter: function (value, row, index) {
                        return new Date(parseInt(value)).Format("yyyy-MM-dd hh:mm");
                    }*/
                }, {
                    title: '核减值(MW)',
                    field: 'val',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '说明',
                    field: 'content',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '备注',
                    field: 'remark',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '手动核减',
                    field: '',
                    width: '8%',
                    formatter: function (value, row, index) {
                        var html = [];
                        html.push('<button class="btn btn-warning btn-xs" style="margin: 5px 5px;">操作</button>');
                        return html.join('');
                    },
                    events: {
                        'click .btn-warning': function (e, value, row, index) {
                            updateOffset(row);

                        }
                    }
                }]
            });

            me.loadData();
        });
    }
    init();
}

function updateOffset(data) {
    // console.log(data);
    var html = [];
    html.push('<div style="margin: 10px">');
    html.push('<text type="text" id="eight_tip" /></br>');
    html.push('<text type="text" id="fifteen_tip" />');
    html.push('</div>');
    layer.open({
        type: 1,
        area: '200px',
        title: '提示',
        btn: ['确定'],
        content: html.join(''),
        success: function (layero, index) {
            var p = {};
            p.startTime = data["startTime"];
            p.endTime = data["endTime"];
            p.offSetVal = data["val"];
            var url = "../FhCorrectManage/offsetUpdate";
            $.post(url, p, function (data) {
                $("#eight_tip").html(data.eight);
                $("#fifteen_tip").html(data.fifteen);
            });
        },
        yes: function (index) {
            layer.close(index);
        }
    });
}

tableFactory.prototype = {

    loadData: function () {
        var me = this;
        var index = layer.load(1);
        var farmid = $('#selectFarm', window.parent.document).val();//获取父页面的元素
        $.getJSON('../FhCorrectManage/selectAll', function (_data) {
            me.data = _data;
            $("#planXd").bootstrapTable("load", _data);
            layer.close(index);
        })
    },

    //加载电站信息

    getWindData: function () {
        var me = this;
        $.getJSON('../FhCorrectManage/selectList', '', function (_data) {
            me.WindData = _data;
            wind = _data;//定义一个全局变量，方便修改的时候调用。
            //layer.close(index);
        })
    },
    //获取电站名称
    getWindById: function (farmid) {
        var typeName = '';
        //var me = this;
        $.each(wind, function (index, item) {
            if (item.type === farmid) {
                typeName = item.typeName;
                return false;
            }
        });
        return typeName;
    },

    save: function () {
        var me = this;
        var html = [];
        html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
        html.push('<tr><td>类型：</td><td><select type="text" class="form-control" id="new-type">');
        $.each(wind, function (index, item) {
            html.push('<option value="' + item.type + '">' + item.typeName + '</option>');
        });
        html.push('</select></td></tr>');
        html.push('<tr><td>发布时间：</td><td><input type="text" class="form-control" id="new-publishtime" /></td></tr>');
        html.push('<tr><td>开始时间：</td><td><input type="text" class="form-control" id="new-starttime" /></td></tr>');
        html.push('<tr><td>结束时间：</td><td><input type="text" class="form-control" id="new-endtime" /></td></tr>');
        html.push('<tr><td>核减值(MW)：</td><td><input type="text" class="form-control" id="new-xdval" /></td></tr>');
        html.push('<tr><td>说明：</td><td><input type="text" class="form-control" id="new-content" /></td></tr>');
        html.push('<tr><td>备注：</td><td><input type="text" class="form-control" id="new-remark" /></td></tr>');
        html.push('</table></div>');
        layer.open({
            type: 1,
            area: '500px',
            title: '添加信息',
            btn: ['确定'],
            //shadeClose: true,//开启遮罩关闭
            content: html.join(''),
            yes: function (index) {
                var p = {
                    type: $("#new-type").val(),
                    publicTime: $("#new-publishtime").val(),
                    startTime: $("#new-starttime").val(),
                    endTime: $("#new-endtime").val(),
                    val: $("#new-xdval").val(),
                    content: $("#new-content").val(),
                    remark: $("#new-remark").val()
                };
                layer.close(index);
                $.ajax({
                    url: "../FhCorrectManage/insert",
                    type: "post",
                    contentType: "application/json",
                    dataType: "json",
                    data: JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                    success: function (data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("添加成功！", {icon: 1});
                        } else {
                            layer.msg("添加失败！", {icon: 2});
                        }
                    },
                    error: function () {
                        layer.msg("添加失败！", {icon: 2});
                    }
                });
            }
        });
    },
    delete: function () {
        var me = this;
        var selects = $('#planXd').bootstrapTable("getSelections");
        if (selects.length > 0) {
            layer.confirm('确定删除?', {icon: 3, title: '提示'}, function (index) {
                //do something
                var deletes = [];
                var id;
                $.each(selects, function (index, item) {
                    deletes.push({
                        fid: item.fid,
                    });
                    //id = item.id;
                });
                $.ajax({
                    url: '../FhCorrectManage/delete',
                    type: 'post',
                    contentType: 'application/json;charset=utf-8', //设置请求头信息
                    dataType: 'json',
                    data: /*{"id":id},*/JSON.stringify(deletes),
                    success: function (data) {
                        if (data > 0) {
                            me.loadData();
                            layer.msg("已删除" + data + "条数据！", {icon: 1});
                        }
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择要删除的信息！", {icon: 0});
        }
    },
    edit: function () {
        var me = this;
        var selects = $('#planXd').bootstrapTable("getSelections");
        var len = selects.length;
        if (len === 1) {
            var editItem = selects[0];
            console.log(editItem);
            var html = [];
            html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
            html.push('<tr><td>类型：</td><td><select type="text" class="form-control" id="edit-type">');
            $.each(wind, function (index, item) {
                if (item.type === editItem.type) {
                    html.push('<option value="' + item.type + '"selected>' + item.typeName + '</option>');
                } else {
                    html.push('<option value="' + item.type + '">' + item.typeName + '</option>');
                }
            });
            html.push('</select></td></tr>');
            html.push('<tr><td>发布时间：</td><td><input type="text" class="form-control" id="edit-publishtime" /></td></tr>');
            html.push('<tr><td>开始时间：</td><td><input type="text" class="form-control" id="edit-starttime" /></td></tr>');
            html.push('<tr><td>结束时间：</td><td><input type="text" class="form-control" id="edit-endtime" /></td></tr>');
            html.push('<tr><td>核减值(MW)：</td><td><input type="text" class="form-control" id="edit-xdval" /></td></tr>');
            html.push('<tr><td>说明：</td><td><input type="text" class="form-control" id="edit-content" /></td></tr>');
            html.push('<tr><td>备注：</td><td><input type="text" class="form-control" id="edit-remark" /></td></tr>');
            html.push('</table></div>');
            layer.open({
                type: 1, area: '500px', title: '修改控制器信息', btn: ['确定'],
                content: html.join(''),
                success: function () {
                    $('#edit-publishtime').val(editItem.publicTime);
                    $('#edit-starttime').val(editItem.startTime);
                    $('#edit-endtime').val(editItem.endTime);
                    $('#edit-xdval').val(editItem.val);
                    $('#edit-content').val(editItem.content);
                    $('#edit-remark').val(editItem.remark);
                },
                yes: function (index) {
                    var p = {
                        fid: editItem.fid,
                        type: $("#edit-type").val(),
                        publicTime: $("#edit-publishtime").val(),
                        startTime: $("#edit-starttime").val(),
                        endTime: $("#edit-endtime").val(),
                        val: $("#edit-xdval").val(),
                        content: $("#edit-content").val(),
                        remark: $("#edit-remark").val(),

                    };
                    layer.close(index);
                    $.ajax({
                        url: "../FhCorrectManage/update",
                        type: "POST",
                        contentType: "application/json",
                        dataType: "json",
                        data: JSON.stringify(p),//转换成字符串。后台使用了RequestBody注解
                        success: function (data) {
                            if (data === true) {
                                me.loadData();
                                layer.msg("修改成功！", {icon: 1});
                            } else {
                                layer.msg("修改失败！", {icon: 2});
                            }
                        },
                        error: function () {
                            alert("添加失败");
                        }
                    });
                }
            });
        } else if (len > 1) {
            layer.msg("只能选择一条信息！", {icon: 0});
        } else if (len === 0) {
            layer.msg("请选择要修改的信息！", {icon: 0});
        }
    }
};

function addListeners(tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        tableObj.edit();
    });
}
